package edu.sias.hyznxfapi.face.baidu.utils;

import com.baidu.aip.face.AipFace;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


import java.util.HashMap;

/**
 * @author PDX
 * @website https://blog.csdn.net/Gaowumao
 * @Date 2024-06-08 17:05
 * @Description
 */
@ConfigurationProperties(prefix = "baidu.face")
@Component
@Data
public class BaiduAiUtils {
//private  String APP_ID;
//private  String API_KEY;
//private  String SECRET_KEY;
//private  String IMAGE_TYPE;
//private  String groupId;


    public static String APP_ID = "118071722";
    public static String API_KEY = "YWcHE8SRAajHrNotReASEB33";
    public static String SECRET_KEY = "ZeYuIjxh4fbojMEF8lG6l5Uk6uOsx4G5";
    public static String IMAGE_TYPE = "BASE64";
    public static String groupId = "1008611";






//    public static void main(String[] args) {
//        System.out.println("APP_ID:" + APP_ID);
//        System.out.println("API_KEY:" + API_KEY);
//        System.out.println("SECRET_KEY:" + SECRET_KEY);
//        System.out.println("IMAGE_TYPE:" + IMAGE_TYPE);
//        System.out.println("groupId:" + groupId);
//    }


    public AipFace client;

    public HashMap<String, String> map = new HashMap<>();

    public BaiduAiUtils() {
        map.put("quality_control", "NORMAL");//图片质量
        map.put("liveness_control", "LOW");//活体检测
    }

    /**
     * TODO
     * 这里注意，这个方法没有正确生效，下面进行了手动调用（待完善）
     */
    @PostConstruct
    public void init() {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    }

    /**
     * 人脸注册，将用户照片存入人脸库中
     *
     * @param userId
     * @param image
     * @return
     */
    public Boolean faceRegister(String userId, String image) {
        //人脸注册
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.addUser(image, IMAGE_TYPE, groupId, userId, map);
        Integer errorCode = res.getInt("error_code");
        System.out.println("???" + errorCode);
        return errorCode == 0 ? true : false;
    }


    /**
     * 人脸删除（直接连带着用户一起删除了，而不是只删除了人脸）
     *
     * @param userId
     * @return
     */
    public Boolean faceDeleteUser(String userId) {
        //人脸注册
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.deleteUser(groupId, userId, map);
        Integer errorCode = res.getInt("error_code");
        System.out.println("???" + errorCode);
        return errorCode == 0 ? true : false;
    }

    /**
     * 人脸更新，更新人脸库中的用户照片
     *
     * @param userId
     * @param image
     * @return
     */
    public Boolean faceUpdate(String userId, String image) {
        //人脸更新
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.updateUser(image, IMAGE_TYPE, groupId, userId, map);
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
    }

    /**
     * 人脸检测。判断上传的图片中是否具有面部信息
     *
     * @param image
     * @return
     */
    public Boolean faceCheck(String image) {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.detect(image, IMAGE_TYPE, map);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject resultObject = res.getJSONObject("result");
            Integer faceNum = resultObject.getInt("face_num");
            return faceNum == 1 ? true : false;
        } else {
            return false;
        }
    }

    /**
     * 人脸检测。判断上传的人脸有几张（这里只能单个检车出一张人脸，多了不行，对接的是数据中台的摄像头获取数据）
     *
     * @param image
     * @return
     */
    public Boolean faceNumberDetect(String image) {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.detect(image, IMAGE_TYPE, map);
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject resultObject = res.getJSONObject("result");
            Integer faceNum = resultObject.getInt("face_num");
            //如果人脸的数量不是1，就返回错误，只允许返回一张人脸
            return faceNum == 1 ? true : false;
        } else {
            return false;
        }
    }

    /**
     * 人脸查找：查找人脸库中最相似的人脸并返回数据
     * 处理：用户的匹配得分（score）大于80分，即可认为是同一个人
     *
     * @param image
     * @return
     */
    public String faceSearch(String image) {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        JSONObject res = client.search(image, IMAGE_TYPE, groupId, map);
        System.out.println(res + "{}{}{}{}{}}{");
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
//            System.out.println("userList"  + userList);
//            System.out.println("userList.length()"  + userList.length());
            if (userList.length() > 0) {
                JSONObject user = userList.getJSONObject(0);
                double score = user.getDouble("score");
//                System.out.println("score = " + score );
                if (score > 80) {
                    return user.getString("user_id");
                }
            }
        }
        return null;
    }

}
